<?php

namespace App\Kuafu\User\Support;

use App\Kuafu\Base\Service\BaseService;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

/**
 * 网易易盾
 */
class NetEaseDun extends NetEaseDunBase
{
    private function do(string $path, array $params): array
    {
        $url  = self::API_DOMAIN . $path;
        $uuid = Str::random(32);

        Log::info("NetEaseDun Curldo uuid:{$uuid} in:{$url}" . json_encode($params, JSON_UNESCAPED_UNICODE));

        $data              = [
            'secretId'    => self::SECRETID,
            'businessId'  => self::BUSINESSID,
            'version'     => self::VERSION,
            'timestamp'   => sprintf("%d", round(microtime(true) * 1000)),
            'nonce'       => $uuid,
        ];
        $data = array_merge($data, $params);

        $data              = $this->toUtf8($data);
        $data['signature'] = $this->gen_signature(self::SECRETKEY, $data);

        $response = (new Client([
            'timeout'     => 10,
            'http_errors' => false, // 不会抛异常
        ]))->request('POST', $url, [
            RequestOptions::FORM_PARAMS => $data,
        ]);
        $res      = json_decode($response->getBody()->getContents(), true) ?? [];

        Log::info("NetEaseDun uuid:{$uuid} out:" . json_encode($res, JSON_UNESCAPED_UNICODE));
        if (isset($res['code']) && $res['code'] == 200) {
            return BaseService::returnData(1, '', $res['data'] ?? []);
        }

        $msg = $res['msg'] ?? '';
        if (!$msg) {
            $msg = "报错信息为空";
        }

        if ($res['code'] == 450) {
            $msg = '登录授权失效，请重试一键登录';
        }

        return BaseService::returnData(0, $msg);
    }

    /**
     * 一键登录获取手机号
     * @param string $token
     * @param string $accessToken
     * @return array
     */
    public function getPhone(string $token, string $accessToken): array
    {
        $data = [
            'token'       => $token,
            'accessToken' => $accessToken,
        ];

        return $this->do('/v1/oneclick/check', $data);
    }

    /**
     * 本机校验
     * @param string $token
     * @param string $accessToken
     * @param string $phone
     * @return array
     */
    public function validPhone(string $token, string $accessToken, string $phone): array
    {
        $data = [
            'token'       => $token,
            'accessToken' => $accessToken,
            'phone'       => $phone,
        ];

        return $this->do('/v1/check', $data);
    }
}
